package cn.lingyangwl.agile.pay.pay.process.payorder;

import cn.lingyangwl.agile.pay.common.service.PayNodeService;
import cn.lingyangwl.agile.pay.common.service.PayOrderService;
import cn.lingyangwl.agile.pay.pay.model.rqrs.ChannelRetMsgExt;
import cn.lingyangwl.agile.pay.pay.model.rqrs.payorder.ClosePayOrderExtRS;
import cn.lingyangwl.agile.pay.constant.PayErrorEnum;
import cn.lingyangwl.framework.core.response.Resp;
import cn.lingyangwl.framework.core.response.RetOps;
import cn.lingyangwl.framework.lock.manager.ILockManager;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.agile.pay.model.rqrs.pay.payorder.ClosePayOrderRQ;
import cn.lingyangwl.agile.pay.pay.process.ChannelPayOrderProcess;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Service
public class CloseOrderProcess {
    @Resource
    private PayOrderService payOrderService;

    @Resource
    private PayNodeService payNodeService;

    @Resource
    private ChannelPayOrderProcess channelPayOrderProcess;

    @Resource
    private ILockManager lockManager;

    /**
     * 关闭订单
     */
    public Resp<ClosePayOrderExtRS> closeOrder(ClosePayOrderRQ rq) {
        if (StringUtils.isAllEmpty(rq.getMchOrderNo(), rq.getPayOrderNo())) {
            throw new BizException("mchOrderNo 和 payOrderNo 不能同时为空");
        }

        String payOrderNo = payOrderService.getPayOrderNo(rq.getMchNo(), rq.getPayOrderNo(), rq.getMchOrderNo());
        if (StringUtils.isEmpty(payOrderNo)) {
            throw new BizException("订单不存在");
        }

        Resp<ChannelRetMsgExt> ret = channelPayOrderProcess.processClosePayOrder(payOrderNo, false);
        ClosePayOrderExtRS bizRes = new ClosePayOrderExtRS();
        bizRes.setChannelRetMsg(ret.getData());

        if (!RetOps.of(ret).isSuccess()) {
            return Resp.fail(PayErrorEnum.CLOSE_ORDER, bizRes);
        }
        return Resp.ok(bizRes);
    }
}
